package cn.gdut.chengcai.admin.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gdut.chengcai.base.ConstantUtil;
import cn.gdut.chengcai.base.JsonUtil;
import cn.gdut.chengcai.base.MemberUtil;
import cn.gdut.chengcai.base.MessageUtil;
import cn.gdut.chengcai.base.Pager;
import cn.gdut.chengcai.base.PagerUtil;
import cn.gdut.chengcai.base.ResponseData;
import cn.gdut.chengcai.entity.BlacklistInfo;
import cn.gdut.chengcai.entity.BlacklistInfoExample;
import cn.gdut.chengcai.entity.MemberInfo;
import cn.gdut.chengcai.entity.MemberInfoExample;
import cn.gdut.chengcai.entity.PersonalInfo;
import cn.gdut.chengcai.entity.PersonalInfoExample;
import cn.gdut.chengcai.param.MemberSearchParam;
import cn.gdut.chengcai.service.BlacklistInfoService;
import cn.gdut.chengcai.service.CountInfoService;
import cn.gdut.chengcai.service.MemberInfoService;
import cn.gdut.chengcai.service.PersonalInfoService;
import cn.gdut.chengcai.vo.MemberInfoVo;
import cn.gdut.chengcai.vo.PersonalInfoVo;

@Controller
@RequestMapping("/admin/member")
public class Admin_MemberController {

	@Autowired
	protected MemberInfoService memberInfoService;

	@Autowired
	protected PersonalInfoService personalInfoService;

	@Autowired
	protected BlacklistInfoService blacklistInfoService;

	@Autowired
	protected CountInfoService countInfoService;

	/**
	 * 个人会员列表页
	 */
	@RequestMapping("/personal/list")
	public String personalList(HttpSession session, ModelMap map) {

		MemberInfoExample example = new MemberInfoExample();
		MemberInfoExample.Criteria criteria = example.createCriteria();
		criteria.andIsDeletedEqualTo(false);
		List<MemberInfo> listTotal = memberInfoService.selectByExample(example);
		Long itemCount = Long.valueOf(String.valueOf(listTotal.size()));
		Pager pager = PagerUtil.getPager(session, itemCount);
		int fromIndex = (pager.getPageNo() - 1) * pager.getPageSize();
		if (fromIndex >= listTotal.size()) {
			fromIndex = 0;
			pager.setPageNo(1);
			session.setAttribute(ConstantUtil.STR_PAGE_NO, "1");
		}
		int toIndex = fromIndex + pager.getPageSize();
		if (toIndex >= listTotal.size()) {
			toIndex = listTotal.size();
		}
		List<MemberInfo> list = listTotal.subList(fromIndex, toIndex);
		try {
			if ((null != list) && (list.size() > 0)) {
				List<MemberInfoVo> voList = new ArrayList<>();
				MemberUtil.fillVoList(list, voList);
				map.put("list", voList);
				session.setAttribute("pager", pager);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/admin/member/personal/list";
	}

	/**
	 * 个人会员信息详情页
	 */
	@RequestMapping("/personal/{id}/preview")
	public String preview(HttpSession session, ModelMap map, @PathVariable Long id) {

		MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(id);

		MemberInfoVo memberVo = new MemberInfoVo();
		PersonalInfoExample personalExample = new PersonalInfoExample();
		personalExample.createCriteria().andSnEqualTo(memberInfo.getSn());

		PersonalInfo personalInfo = personalInfoService.selectByExample(personalExample).get(0);
		PersonalInfoVo personVo = new PersonalInfoVo();
		try {
			MemberUtil.fillVo(memberInfo, memberVo);
			MemberUtil.fillVo(personalInfo, personVo);
			map.put("memberVo", memberVo);
			map.put("personVo", personVo);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/admin/member/personal/preview";
	}

	/**
	 * 删除操作
	 */
	@RequestMapping(value = "/personal/delete/{sn}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> deleteAction(@PathVariable String sn) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			// 逻辑删除
			MemberInfoExample memberExample = new MemberInfoExample();
			memberExample.createCriteria().andSnEqualTo(sn);
			MemberInfo member = memberInfoService.selectByExample(memberExample).get(0);
			member.setIsDeleted(true);
			memberInfoService.updateByPrimaryKey(member);

			PersonalInfoExample personalExample = new PersonalInfoExample();
			memberExample.createCriteria().andSnEqualTo(sn);
			PersonalInfo person = personalInfoService.selectByExample(personalExample).get(0);
			person.setIsDeleted(true);
			personalInfoService.updateByPrimaryKey(person);

			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

	/**
	 * 移入黑名单操作
	 */
	@RequestMapping(value = "/personal/shiftIn/{memberId}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> shiftInAction(@PathVariable Long memberId) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
			memberInfo.setIsAllowLogin(false);
			memberInfoService.updateByPrimaryKey(memberInfo);

			// 插入黑名单表
			BlacklistInfo blacklistInfo = new BlacklistInfo();
			blacklistInfo.setMemberId(memberId);
			blacklistInfo.setMemberSn(memberInfo.getSn());
			blacklistInfo.setMemberUsername(memberInfo.getUsername());
			blacklistInfo.setIsAdmin(false);
			blacklistInfo.setCreateTime(new Date());
			blacklistInfoService.insert(blacklistInfo);

			result.setMessage("操作成功！");
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
		}
		return result;
	}

	/**
	 * 移出黑名单操作
	 */
	@RequestMapping(value = "/personal/shiftOut/{memberId}", method = { RequestMethod.POST })
	@ResponseBody
	public ResponseData<Object> shiftOutAction(@PathVariable Long memberId) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {

			MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(memberId);
			memberInfo.setIsAllowLogin(true);
			memberInfoService.updateByPrimaryKey(memberInfo);

			// 删除
			BlacklistInfoExample example = new BlacklistInfoExample();
			example.createCriteria().andMemberIdEqualTo(memberId).andMemberSnEqualTo(memberInfo.getSn())
					.andMemberUsernameEqualTo(memberInfo.getUsername()).andIsAdminEqualTo(false);
			BlacklistInfo blacklistInfo = blacklistInfoService.selectByExample(example).get(0);
			blacklistInfoService.deleteByExample(example);

			result.setMessage("操作成功！");
			result.setIsSuccess(true);
		} catch (Exception e) {
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 会员搜索页
	 */
	@RequestMapping("/personal/search")
	public String search(HttpSession session, ModelMap map) {

		if (session.getAttribute(ConstantUtil.SESSION_SEARCH_PARAM) instanceof MemberSearchParam) {

		} else {
			session.setAttribute(ConstantUtil.SESSION_SEARCH_PARAM, null);
		}
		// filter必须放最后面，不然，pager会被覆盖！！！
		try {
			MemberUtil.filter(session, map, memberInfoService, null);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/admin/member/personal/search";
	}

	/**
	 * 获取会员的过滤条件
	 */
	@RequestMapping(value = "/personal/resetSearchFilterAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> resetSearchFilterAction(@RequestBody String jsonString, HttpServletRequest request,
			HttpSession session) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);
		try {
			MemberSearchParam param = (MemberSearchParam) session.getAttribute(ConstantUtil.SESSION_SEARCH_PARAM);
			if (param == null) {
				param = new MemberSearchParam();
				MemberUtil.resetSearchParamConstant(param);
			}
			result.setData(param);
			result.setIsSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}

		return result;
	}

	/**
	 * 会员的搜索过滤
	 */
	@RequestMapping(value = "/personal/reloadDataAction", method = RequestMethod.POST)
	@ResponseBody
	public ResponseData<Object> reloadDataAction(@RequestBody String jsonString, HttpSession session, ModelMap map) {
		ResponseData<Object> result = new ResponseData<>();
		result.setIsSuccess(false);

		MemberSearchParam param = (MemberSearchParam) JsonUtil.fromJson(jsonString, MemberSearchParam.class);
		try {
			List<MemberInfoVo> voList = MemberUtil.filter(session, map, memberInfoService, param);
			result.setData(voList);
			result.setPager((Pager) session.getAttribute("pager"));
			result.setIsSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			result.setMessage(MessageUtil.SYSTEM_ERROR);
			// log.error(e.getMessage(), e);
		}
		return result;
	}

}